<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @selection-change="selectionChange"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot="menuLeft">
        <el-button size="small" type="danger" @click.stop="handleDelete">删除 </el-button>
      </template>
      <template slot-scope="{ row }" slot="isAllowEdit">
        <span>{{ row.isAllowEdit ? '只读' : '' }}</span>
      </template>
      <template slot-scope="{ row }" slot="isAllowEditForm">
        <el-checkbox v-model="form.isAllowEdit">只读</el-checkbox>
      </template>
      <template slot-scope="{ row }" slot="datasourceForm">
        <div class="custom-config"><i class="el-icon-vertical-bar"></i>自定义选项配置</div>
        <el-form label-width="150" :model="form" class="ml20" ref="elForm" v-if="type !== 'view'">
          <el-form-item
            style="margin-bottom: 16px"
            v-for="(item, index) in form.options"
            :label="'自定义选项' + (index + 1) + ':'"
            :key="item.value + index"
            :prop="'options.' + index + '.value'"
            :rules="{
              required: true,
              message: `${'自定义选项' + (index + 1)}不能为空`,
              trigger: 'blur'
            }"
          >
            <el-input v-model="item.value" style="width: 300px"></el-input>
            <el-button
              type="text"
              @click.stop="handleSetDefaultValue(index)"
              class="ml20"
              :style="{ color: item.value && !item.checked ? '#409eff' : '#c0c4cc' }"
              :disabled="!item.value"
              >{{ item.checked ? '默认值' : '设为默认值' }}</el-button
            >
            <el-button type="text" icon="el-icon-circle-plus-outline" @click.stop="handleAddValue(index)" class="ml10"></el-button>
            <el-button type="text" style="color: #f56c6c" icon="el-icon-delete" @click.stop="handleDeleteValue(index)" class="ml10" v-show="index !== 0"></el-button>
          </el-form-item>
        </el-form>
        <div v-else>
          <avue-form :option="detailOption" v-model="form"></avue-form>
        </div>
      </template>
    </avue-crud>
  </basic-container>
</template>
<script>
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
import { addAttributeConfig, getAttributeConfig, removeAttributeConfig } from '@/api/system/custom-attribute-config';
export default {
  name: 'expendPropertyLibrary', // 会渲染成传入的componentName
  components: {
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      form: {},
      query: {},
      detailOption: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      data: [],
      option: {
        height: 'calc(100vh - 450px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtnText: '详情',
        viewBtn: true,
        editBtn: true,
        delBtn: true,
        addBtn: true,
        indexLabel: '序号',
        columnBtn: false,
        selection: true,
        dialogCustomClass: 'custom-dialog',
        column: [
          {
            label: '字段名称',
            prop: 'lableCnName',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入字段名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '字段编码',
            prop: 'attributeKey',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入字段编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '字段类型',
            prop: 'controlType',
            type: 'select',
            search: true,
            dicData: [
              { label: '文本', value: 'input' },
              { label: '文本域', value: 'text' },
              { label: '数字', value: 'number' },
              { label: '日期', value: 'date' },
              { label: '时间', value: 'time' },
              { label: '日期时间', value: 'datetime' },
              { label: '下拉单选(固定值)', value: 'singleSelect' },
              { label: '下拉多选(固定值)', value: 'multiSelect' }
            ],
            control: (val, form) => {
              if (val) {
                if (val === 'singleSelect' || val === 'multiSelect') {
                  return {
                    defaultValue: {
                      display: false
                    },
                    datasource: {
                      display: true
                    }
                  };
                } else {
                  return {
                    defaultValue: {
                      display: true
                    },
                    datasource: {
                      display: false
                    }
                  };
                }
              }
            },
            rules: [
              {
                required: true,
                message: '请选择字段类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '字段属性',
            prop: 'isAllowEdit',
            formsolt: true
          },
          {
            label: '引导文字',
            prop: 'defaultTipMessage'
          },
          {
            label: '默认值',
            prop: 'defaultValue'
          },
          {
            label: '状态',
            prop: 'enabled',
            type: 'switch',
            value: true,
            dicData: [
              { label: '禁用', value: false },
              { label: '启用', value: true }
            ],
            row: true,
            html: true,
            formatter: (val) => {
              switch (val.enabled) {
                case true:
                  return `<span class="stateWords-success">启用</span>`;
                case false:
                  return `<span class="stateWords-danger">禁用</span>`;
                default:
                  break;
              }
            }
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            overHidden: true,
            span: 24
          },
          {
            label: '',
            prop: 'datasource',
            labelWidth: 0,
            type: '',
            formslot: true,
            hide: true,
            display: false,
            span: 24
          },
          {
            label: '创建人',
            prop: 'createUserName',
            display: false
          },
          {
            label: '创建时间',
            prop: 'createTime',
            display: false
          }
        ]
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      return this.selectionList.map((i) => i.id).join(',');
    }
  },
  methods: {
    async rowSave(row, done, loading) {
      try {
        const params = this._cloneDeep(row);
        if (row.controlType === 'singleSelect' || row.controlType === 'multiSelect') {
          const checkRes = await this.$refs.elForm.validate();
          if (!checkRes) {
            loading();
            return;
          }
          const options = JSON.stringify(row.options.map((item) => ({ value: item.value, checked: item.checked })));
          params.options = options;
        } else {
          params.options = '';
        }
        const res = await addAttributeConfig(params);
        await this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        done();
      } catch (e) {
        console.log(e);
        loading();
      }
    },
    async rowUpdate(row, index, done, loading) {
      try {
        const params = this._cloneDeep(row);
        if (row.controlType === 'singleSelect' || row.controlType === 'multiSelect') {
          const checkRes = await this.$refs.elForm.validate();
          if (!checkRes) {
            loading();
            return;
          }
          const options = JSON.stringify(row.options.map((item) => ({ value: item.value, checked: item.checked })));
          params.options = options;
        } else {
          params.options = '';
        }
        const res = await addAttributeConfig(params);
        await this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        done();
      } catch (e) {
        console.log(e);
        loading();
      }
    },
    rowDel(row) {
      this.$confirm(`是否确认将${row.lableCnName}扩展属性删除？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await removeAttributeConfig(row.id);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.onLoad(this.page);
        } catch (e) {
          console.warn(e);
        }
      });
    },
    handleDelete() {
      this.$confirm('是否确认将勾选则扩展属性删除？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await removeAttributeConfig(this.ids);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.onLoad(this.page);
        } catch (e) {
          console.warn(e);
        }
      });
    },
    beforeOpen(done, type) {
      this.type = type;
      if (this.form.options) {
        const colum = [];
        const options = JSON.parse(this.form.options);
        this.form.options = options.map((item, index) => {
          if (type === 'view') {
            colum.push({ label: `自定义选项${index + 1}`, value: item.value, prop: `自定义选项${index + 1}` });
          }
          return { label: '自定义选项', ...item };
        });
        this.detailOption = {
          submitBtn: false,
          labelWidth: 120,
          emptyBtn: false,
          detail: true,
          column: colum
        };
      } else {
        this.form.options = [{ label: '自定义选项', value: '', checked: false }];
      }

      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    handleSetDefaultValue(index) {
      const form = this._cloneDeep(this.form);
      form.options.forEach((item, ind) => {
        if (ind === index) {
          item.checked = true;
        } else {
          item.checked = false;
        }
      });
      this.form = form;
      // this.form.value.splice(index, 1, { label: '自定义选项', val: '', isDefault: true });
    },
    handleAddValue(index) {
      this.form.options.push({ label: '自定义选项', value: '', checked: false });
    },
    handleDeleteValue(index) {
      this.form.options.splice(index, 1);
    },
    async onLoad(page, params = {}) {
      this.loading = true;
      try {
        const res = await getAttributeConfig(page.currentPage, page.pageSize, Object.assign(params, this.query));
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.selectionClear();
      } catch (e) {
        console.warn(e);
      } finally {
        this.loading = false;
      }
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    }
  }
};
</script>
<style lang="scss" scoped>
.ml20 {
  margin-left: 20px;
}

.ml10px {
  margin-left: 10px;
}
.custom-config {
  font-weight: bold;
  font-size: 16px;
}
.custom-dialog {
  max-height: 450px;
}
::v-deep .el-form-item__error {
  left: 100px;
}

.custom-table {
  width: 50%;
  border: 1px solid #ebeef5;
}
.flex-box {
  display: flex;
  width: 100%;
}
</style>
